const fs = require('fs');
const path = require('path');

// 修复全局加载组件位置的脚本
function fixGlobalLoadingPosition() {
  console.log('开始修复全局加载组件位置...');
  
  // 需要修复的页面列表
  const pagesToFix = [
    'pages/village/cases/index.wxml',
    'pages/common/about/index.wxml',
    'pages/village/open/index.wxml',
    'pages/service/agriculture-rural/machinery-subsidy/index.wxml',
    'pages/service/comprehensive-governance/security-incident-report/index.wxml',
    'pages/service/certificate-services/resident-proof/index.wxml',
    'pages/admin/feedback/index.wxml',
    'pages/village/complaints/index.wxml',
    'pages/service/public-services/streetlight-repair/index.wxml',
    'pages/service/civil-affairs/pension-subsidy/index.wxml',
    'pages/village/notice-detail/index.wxml',
    'pages/admin/stats/index.wxml',
    'pages/admin/chart-analysis/index.wxml',
    'pages/admin/index/index.wxml',
    'pages/admin/users/index.wxml',
    'pages/admin/cases/detail/index.wxml',
    'pages/admin/notices/index.wxml',
    'pages/user/activities/index.wxml',
    'pages/admin/activities/index.wxml',
    'pages/activity/detail/index.wxml',
    'pages/user/mine/profile/index.wxml',
    'pages/auth/register/index.wxml',
    'pages/auth/bind-email/index.wxml',
    'pages/auth/login/index.wxml',
    'pages/auth/forgot-password/index.wxml',
    'pages/user/progress/index.wxml',
    'pages/user/favorites/index.wxml',
    'pages/service/comprehensive-governance/dispute-mediation/index.wxml',
    'pages/admin/cases/index.wxml',
    'pages/common/search-results/index.wxml'
  ];
  
  let fixedCount = 0;
  
  pagesToFix.forEach(pagePath => {
    const fullPath = path.join(__dirname, '..', pagePath);
    
    if (fs.existsSync(fullPath)) {
      try {
        const content = fs.readFileSync(fullPath, 'utf8');
        
        // 检查是否有错误的global-loading组件位置
        const wrongPattern = /^<!-- 全局加载组件 -->\s*<global-loading[\s\S]*?<\/global-loading>\s*<\/view>\s*$/m;
        
        if (wrongPattern.test(content)) {
          // 修复错误的组件位置
          const fixedContent = content.replace(
            wrongPattern,
            (match) => {
              // 提取global-loading组件内容
              const componentMatch = match.match(/<global-loading[\s\S]*?<\/global-loading>/);
              if (componentMatch) {
                const component = componentMatch[0];
                // 将组件移到正确的位置（在</view>之前）
                return match.replace(component, '').replace('</view>', `  ${component}\n</view>`);
              }
              return match;
            }
          );
          
          // 更精确的修复方法
          const lines = content.split('\n');
          let fixedLines = [];
          let globalLoadingComponent = '';
          let foundWrongPosition = false;
          
          for (let i = 0; i < lines.length; i++) {
            const line = lines[i];
            
            // 找到错误的global-loading组件开始
            if (line.trim() === '<!-- 全局加载组件 -->' && i < lines.length - 2) {
              foundWrongPosition = true;
              // 收集整个组件
              let j = i;
              while (j < lines.length && !lines[j].includes('</global-loading>')) {
                globalLoadingComponent += lines[j] + '\n';
                j++;
              }
              if (j < lines.length) {
                globalLoadingComponent += lines[j] + '\n';
                i = j; // 跳过已处理的组件行
                continue;
              }
            }
            
            // 如果遇到</view>且之前有错误的组件，则插入组件
            if (line.trim() === '</view>' && foundWrongPosition && globalLoadingComponent) {
              fixedLines.push('  <!-- 全局加载组件 -->');
              fixedLines.push(globalLoadingComponent.trim());
              fixedLines.push('</view>');
              globalLoadingComponent = '';
              foundWrongPosition = false;
            } else if (!foundWrongPosition) {
              fixedLines.push(line);
            }
          }
          
          const finalContent = fixedLines.join('\n');
          
          if (finalContent !== content) {
            fs.writeFileSync(fullPath, finalContent, 'utf8');
            console.log(`✅ 已修复: ${pagePath}`);
            fixedCount++;
          } else {
            console.log(`⚠️  无需修复: ${pagePath}`);
          }
        } else {
          console.log(`⚠️  无需修复: ${pagePath}`);
        }
      } catch (error) {
        console.error(`❌ 修复失败: ${pagePath}`, error.message);
      }
    } else {
      console.log(`⚠️  文件不存在: ${pagePath}`);
    }
  });
  
  console.log(`\n修复完成！共修复了 ${fixedCount} 个文件`);
}

// 运行修复脚本
if (require.main === module) {
  fixGlobalLoadingPosition();
}

module.exports = { fixGlobalLoadingPosition };
